package com.xgggh.redpack.ui.home;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.xgggh.redpack.R;
import com.xgggh.redpack.base.ui.BaseFragment;
import com.xgggh.redpack.databinding.HomeFragmentBinding;
import com.xgggh.redpack.domain.redpack.Pack;
import com.xgggh.redpack.domain.redpack.RedPackType;
import com.xgggh.redpack.ui.home.viewbinder.HomeViewBinder;
import com.xgggh.redpack.ui.home.viewbinder.HomeViewUndefinedBinder;
import com.xgggh.redpack.ui.redpack.QrCodeScannerActivity;
import java.util.List;
import javax.inject.Inject;
import dagger.android.support.AndroidSupportInjection;
import io.reactivex.subscribers.DisposableSubscriber;
import me.drakeet.multitype.ClassLinker;
import me.drakeet.multitype.ItemViewBinder;
import model.Rsp;
import model.Status;
import viewmodel.RedPackViewModel;
import viewmodel.ViewModelFactory;

public class HomeFragment extends BaseFragment {

    HomeFragmentBinding mBinding;
    @Inject
    ViewModelFactory factory;
    RedPackViewModel model;


    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.home_fragment, container, false);
        return mBinding.getRoot();
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.home, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_camera:
                startActivity(new Intent(getContext(), QrCodeScannerActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        adapter.register(Pack.class).to(
                new HomeViewBinder()
                ,new HomeViewUndefinedBinder()
        )
        .withClassLinker(new ClassLinker<Pack>() {
            @NonNull
            @Override
            public Class<? extends ItemViewBinder<Pack, ?>> index(int position, @NonNull Pack pack) {
                if (pack.getCategory()==RedPackType.mianfei
                        ||pack.getCategory()==RedPackType.duizhan
                        ||pack.getCategory()==RedPackType.saoma
                        ||pack.getCategory()==RedPackType.zhongchou
                        ||pack.getCategory()==RedPackType.gushi
                        ||pack.getCategory()==RedPackType.jielong
                ){
                    return HomeViewBinder.class;
                }else{
                    return HomeViewUndefinedBinder.class;
                }
            }
        });
        adapter.setItems(items);
        mBinding.appBarHome.contentHome.recyclerView.setAdapter(adapter);
        mBinding.appBarHome.contentHome.twinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                getRedPack(firstPage());
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                getRedPack(nextPage());
            }
        });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getUserVisibleHint() && items.size()==0){
            getRedPack(currentPage());
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onAttach(Context context) {
        AndroidSupportInjection.inject(this);
        super.onAttach(context);
        model= ViewModelProviders.of(this,factory).get(RedPackViewModel.class);
    }

    private  void getRedPack(final int page){
        Pack pack=new Pack();
        pack.setLatitude(30.753774);
        pack.setLongitude(103.939783);
        model.getRedPackList(page,size,pack)
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this)))
                .subscribe(new DisposableSubscriber<Rsp<List<Pack>>>() {
                    @Override
                    public void onNext(Rsp<List<Pack>> listRsp) {
                        redPackList(page,listRsp);
                    }

                    @Override
                    public void onError(Throwable t) {
                        clear(page);
                    }

                    @Override
                    public void onComplete() {
                        clear(page);
                    }
                });
    }

    private void clear(int page){
        if (page==firstPage()){
            mBinding.appBarHome.contentHome.twinklingRefreshLayout.finishRefreshing();
        }else{
            mBinding.appBarHome.contentHome.twinklingRefreshLayout.finishLoadmore();
        }
    }
    private void redPackList(int page,Rsp<List<Pack>> rsp){
        if (rsp.getStatus()!= Status.OK){
            Toast.makeText(getContext(), rsp.getMsg(), Toast.LENGTH_SHORT).show();
            return;
        }
        List<Pack> redPacks= rsp.getData();
        if (page==firstPage()){
            if (redPacks==null || redPacks.size()==0){
                // 没有数据，显示空界面，点击跳转发红包界面
                return;
            }
            items.clear();
            items.addAll(redPacks);
            adapter.notifyDataSetChanged();
        }else if (page==nextPage()){
            if (redPacks==null || redPacks.size()==0){
                Toast.makeText(getBaseActivity(), "没有更多数据了", Toast.LENGTH_SHORT).show();
                return;
            }
            items.addAll(redPacks);
            adapter.notifyDataSetChanged();
        }
        if (redPacks!=null && redPacks.size()!=0){
            setCurrentPage(page);
        }

    }
}
